﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Windows.Input;
using MCDomain.DataAccess;
using MCDomain.Model;
using UIShared.Commands;
using MContracts.ViewModel.Helpers;
using MediatorLib;
using McUIBased.Commands;

namespace MContracts.ViewModel
{
    public class StageResultsViewModel: ContractdocBaseViewModel
    {
        public StageResultsViewModel(IContractRepository repository)
            : base(repository)
        {
            ViewMediator.Register(this);
        }

        [MediatorMessageSink(RequestRepository.REFRESH_RESULT_SCHEDULE, ParameterType = typeof(Stageresult))]
        public void AddedResult(Stageresult stageresult)
        {
            resultsBindingList = null;
            OnPropertyChanged("ResultsBindingList");
        }

        [MediatorMessageSink(RequestRepository.REFRESH_RESULT_SCHEDULE_STAGE, ParameterType = typeof(Stage))]
        public void StageChanged(Stage stage)
        {
            resultsBindingList = null;
            OnPropertyChanged("ResultsBindingList");
        }


        [MediatorMessageSink(RequestRepository.REFRESH_RESULT_SCHEDULE_GENERAL, ParameterType = typeof(Schedule))]
        public void ScheduleChanged(Schedule schedule)
        {
            resultsBindingList = null;
            OnPropertyChanged("ResultsBindingList");
        }


        private AutoSubmitCommand createResultCommand;
        private AutoSubmitCommand deleteResultCommand;

        private IBindingList resultsBindingList;
        public IBindingList ResultsBindingList
        {
            get
            {
                if (resultsBindingList == null)
                {
                    if ((WrappedDomainObject as Contractdoc).Schedulecontracts.Count > 0)
                    {
                        resultsBindingList = new BindingList<Stageresult>();
                        foreach (Stage s in SelectedSchedule.Schedule.Stages)
                        {
                            foreach (Stageresult sr in s.Stageresults)
                            {
                                resultsBindingList.Add(sr);
                            }
                        }
                    }
                }
                return resultsBindingList;
            }
        }

        public IEnumerable<Schedulecontract> Schedulecontracts
        {
            get { return ContractObject.Schedulecontracts.Where(c => c.Schedule != null); }
        }

        private Schedulecontract _selectedschedule;
        /// <summary>
        /// выбранный КП
        /// </summary>
        public Schedulecontract SelectedSchedule
        {
            get
            {
                if (_selectedschedule == null) _selectedschedule = Schedulecontracts.FirstOrDefault();
                return _selectedschedule;
            }
            set 
            { 
                _selectedschedule = value;
                resultsBindingList = null;
                OnPropertyChanged("SelectedSchedule");
                OnPropertyChanged("Stages");
                OnPropertyChanged("ResultsBindingList");
            }
        }

        private Stageresult selectedResult;
        public Stageresult SelectedResult
        {
            get
            {
                return selectedResult;
            }
            set
            {
                selectedResult = value;
            }
        }

        public IEnumerable<Economefficiencytype> Economefficiencytypes
        {
            get
            {
                return Repository.Economefficiencytypes;
            }
        }

        public IEnumerable<Ntpview> Ntpviews
        {
            get
            {
                return Repository.Ntpviews;
            }
        }

        public IEnumerable<Ntpsubview> Ntpsubviews
        {
            get
            {
                return Repository.Ntpsubviews;
            }
        }

        private IBindingList stages;
        public IBindingList Stages
        {
            get
            {
                if (stages == null)
                {
                    if (SelectedSchedule != null)
                    {
                        stages = SelectedSchedule.Schedule.Stages.GetNewBindingList();
                    }
                }
                return stages;
            }
        }
        
        protected override void Save()
        {
            
        }

        protected override bool CanSave()
        {
            return ValidateResults();
        }

        public override string DisplayName
        {
            get
            {
                return "Результаты";
            }
        }

        public override string Error
        {
            get
            {
                String error = String.Empty;

                if (ResultsBindingList != null)
                {
                    foreach (Stageresult stageresult in this.ResultsBindingList)
                    {
                        error += stageresult.Error + "\n";
                    }
                }

                if (error != String.Empty)
                    return error;

                return null;
            }
        }

        public void OnErrorChanged()
        {
            ViewMediator.NotifyColleagues(RequestRepository.REQUEST_ERROR_CHANGED, Error);
        }

        #region ResultsCommands

        public ICommand CreateResultCommand
        {
            get
            {
                return createResultCommand ??
                       (createResultCommand = new AutoSubmitCommand(CreateResult, x => CanCreateResult, Repository));
            }
        }

        private void CreateResult(object o)
        {
            var result = new Stageresult();
            ResultsBindingList.Add(result);
            result.PropertyChanged += stageresult_PropertyChanged;
            OnPropertyChanged("ResultsBindingList");
            
        }

        public ICommand DeleteResultCommand
        {
            get
            {
                return deleteResultCommand ??
                       (deleteResultCommand = new AutoSubmitCommand(DeleteResult, x => CanDeleteResult, Repository));
            }
        }

        private void DeleteResult(object o)
        {
            Stage s = selectedResult.Stage;
            if (s != null)
            {
                Repository.DeleteStateResult(selectedResult);
                s.Stageresults.Remove(selectedResult);
            }
            resultsBindingList = null;
            OnPropertyChanged("ResultsBindingList");
            ViewMediator.NotifyColleagues(RequestRepository.REFRESH_RESULT, s);            
            //ResultsBindingList.Remove(selectedResult);


        }

        




















        public bool CanCreateResult
        {
            get
            {
                return ResultsBindingList != null;
            }
        }

        public bool CanDeleteResult
        {
            get { return selectedResult != null; }
        }


        #endregion

        public void CreateParameters()
        {
           
            var Parameters = selectedResult.Economefficiencytype.Efficienceparametertypes;
            /*
           foreach (var Param in selectedResult.ParametersBindingList)
           {
               if ((Param as Efparameterstageresult).Stageresult != null)
               {
                   Repository.DeleteEfparamStageresult(Param as Efparameterstageresult);
               }
           }

           try
           {
               selectedResult.ParametersBindingList.Clear();
           }
           catch
           {
           } */

            selectedResult.ParametersBindingList.Clear();

            foreach (var parameter in Parameters)
            {
                selectedResult.ParametersBindingList.Add(new Efparameterstageresult()
                {
                    Economefficiencyparameter = parameter.Economefficiencyparameter
                });
            }

            OnPropertyChanged("SelectedResult");
        }

        private bool ValidateResults()
        {
            if (ResultsBindingList != null)
            {
                foreach (var stageresult in ResultsBindingList)
                {
                    if (!string.IsNullOrEmpty((stageresult as Stageresult).Error)) return false;
                }
            }
            return true;
        }

        public void AddResult(Stage stage)
        {
            ViewMediator.NotifyColleagues(RequestRepository.REFRESH_RESULT, stage);
        }

        public void UpdateResult()
        {
            ViewMediator.NotifyColleagues(RequestRepository.REFRESH_RESULT, selectedResult.Stage);
        }


        void stageresult_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {

            var stageresult = sender as Stageresult;
            ViewMediator.NotifyColleagues(RequestRepository.REFRESH_RESULT, stageresult.Stage);
            ViewMediator.NotifyColleagues(RequestRepository.REFRESH_RESULT_SCHEDULE, stageresult); 

        }

    }
}
